package com.example.demo.controller.Test;

import com.example.demo.common.Result;
import com.example.demo.mapper.ImgMapper;
import com.example.demo.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.example.demo.utils.AliOSSUtils;

import java.io.IOException;
import java.time.LocalDateTime;


@RestController
@Slf4j
public class UploadImgController {
    @Autowired
    private AliOSSUtils aliOSSUtils;
//ioc容器 回收对象机制
    @Autowired
    private ImgMapper imgMapper;

    //    @PostMapping("/upload")//这里的变量名image要与前端对应
//    public Result upload(String username, Integer age,MultipartFile image) throws IOException {
//        //把文件的内容存储到本地磁盘上
//        String originalFilename = image.getOriginalFilename();
//        //保证文件的名字是唯一的,从而防止文件覆盖
//        String filename = UUID.randomUUID().toString()+originalFilename.substring(originalFilename.lastIndexOf("."));
//        image.transferTo(new File("D:\\lj\\"+filename));
//
//        return Result.success();
//    }
    @PostMapping("/upload")
    public Result upload(MultipartFile image,String account) throws IOException {
        System.out.println(account);
        log.info("文件上传,文件名:{}", image.getOriginalFilename());
        //调用阿里云工具类上传
        String url = aliOSSUtils.upload(image);

        log.info("阿里云文件上传完成,文件访问的url:{}", url);

        User user = new User();
        user.setAccount(account);
        user.setImg(url);
        imgMapper.updateImg(user);
        log.info("数据库文件上传完成,文件访问的url:{}", url);
        return Result.success(url);
    }

    @GetMapping("/load/{account}")
    public Result load(@PathVariable String account){
        User user = new User();
        user.setAccount(account);
        return Result.success(imgMapper.getImg(user));
    }
}
